package com.demo.common;

import org.apache.commons.collections.map.HashedMap;
import org.joda.time.DateTime;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

/**
 * Created by liushaokang on 2017/3/14.
 */
public class Constants {

    public static final String USER = "loginUser";
    public static final String PHONE_CODE = "PHONE_CODE";
    public static final String CURRENT_WX_USER = "CURRENT_WX_USER";
    public static final String CURRENT_SP = "current";
    public static final String SHARE = "user_share"; //分享用户IID
    public static final String LOGIN_TYPE_PC = "pc"; //登录用户账户类型：WEB应用
    public static final String LOGIN_TYPE_WX = "wx"; //登录用户账户类型：微信公众号
    public static final String SUPER_MANAGER_ROLE_ID = "3"; //超级管理员角色ID

    public static final String WXUserTypeWX = "WX"; // USER WX 数据类型, WX：微信账户，模拟热
    public static final String WXUserTypePC = "PC"; // USER WX 数据类型, WX：微信账户，模拟热
    public static final String KAPTCHA_SESSION_KEY = "KAPTCHA_SESSION_KEY";

    public static String orderpaperPath = null;
    public static String thumbnailPath = null;
    public static String nginxVisitUrl = null;
    public static String token = null;
    public static String encodingAESKey = null;
    public static String url = null;
    public static String apikey = null;
    public static String tmpid = null;
    public static String domain = null;

    /***
     * 数据状态
     */
    public static String DATA_DELETED = "0"; // 数据逻辑删除
    public static String DATA_ONLINE = "1"; // 数据上线
    public static String DATA_OFFLINE = "2"; // 数据下线

    /**
     * 微信消息模板
     */
    public static String tmplCreateOrder = null;
    public static String tmplUpdateOrderStatus = null;

    public static String tmplReturnedCommission = null;
    public static String tmplApplyServiceSuccess = null;
    public static String tmplWithDrawSuccess = null;
    public static String tmplUpdateOrderPrice = null; // 订单价格变更
    public static String tmplNewVipJoin = null; // 新会员加入提醒

    public static final String slat = "mn9-+`!&*";

    public void init() {
        Constants.orderpaperPath = this.orderpaperPath;
        Constants.thumbnailPath = this.thumbnailPath;
        Constants.nginxVisitUrl = this.nginxVisitUrl;
        Constants.token = this.token;
        Constants.encodingAESKey = this.encodingAESKey;
        Constants.url = this.url;
        Constants.apikey = this.apikey;
        Constants.tmpid = this.tmpid;
        Constants.domain = this.domain;
        Constants.tmplCreateOrder = this.tmplCreateOrder;
        Constants.tmplUpdateOrderStatus = this.tmplUpdateOrderStatus;
        Constants.tmplApplyServiceSuccess = this.tmplApplyServiceSuccess;
        Constants.tmplWithDrawSuccess = this.tmplWithDrawSuccess;
        Constants.tmplReturnedCommission = this.tmplReturnedCommission;
        Constants.tmplUpdateOrderPrice = this.tmplUpdateOrderPrice;
        Constants.tmplNewVipJoin = this.tmplNewVipJoin;
    }

    /**
     * 订单号生成
     */
    public static String createOrderNO() {
        char[] chrs = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
                'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
                'X', 'Y', 'Z'};

        int max = 26;
        int min = 0;
        int index = new Random().nextInt(max) % (max - min + 1) + min;

        return new StringBuilder(30)
                .append("XHP")
                .append(DateTime.now().toString("yyyyMMdd-"))
//                .append(chrs[index])
//                .append(System.currentTimeMillis())
                .append(String.valueOf(System.currentTimeMillis()).substring(8))
                .toString();
    }

    public static void main(String[] arg) {
        System.out.println(generateServiceNO("D", generateLimitNumberStr(30, 6)));
//        System.out.println(getTimeMillisSequence());
//        System.out.println(PrintContract.number2CNMontrayUnit(new BigDecimal(4500000.000)));
    }

    public static String getOrderIdByUUId() {
        int machineId = 1;//最大支持1-9个集群机器部署
        int hashCodeV = UUID.randomUUID().toString().hashCode();
        if (hashCodeV < 0) {//有可能是负数
            hashCodeV = -hashCodeV;
        }
        // 0 代表前面补充0
        // 4 代表长度为4
        // d 代表参数为正数型
        return machineId + String.format("%015d", hashCodeV);
    }


    /**
     * 生成业务编码
     *
     * @param prefix
     * @return
     */
    public static String generateServiceNO(String prefix) {
        char[] chrs = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
                'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
                'X', 'Y', 'Z'};

        int max = 26;
        int min = 0;
        int index = new Random().nextInt(max) % (max - min + 1) + min;
        String ms = String.valueOf(System.currentTimeMillis());
        ms = ms.substring(ms.length() - 3);
        return new StringBuilder(30)
                .append(prefix)
                .append("HP")
                .append(DateTime.now().toString("yyyyMMdd-HHmmSS"))
                .append(chrs[index])
//                .append(System.currentTimeMillis())
                .append('-')
                .append(ms)
                .toString();
    }

    public static String generateServiceNO(String prefix, String appender) {
        char[] chrs = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
                'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
                'X', 'Y', 'Z'};

        int max = 26;
        int min = 0;
        int index = new Random().nextInt(max) % (max - min + 1) + min;
//        String ms = String.valueOf(System.currentTimeMillis());
//        ms = ms.substring(ms.length() - 3);
        return new StringBuilder(30)
                .append(prefix)
                .append("HP")
                .append(DateTime.now().toString("yyyyMMdd"))
//                .append(chrs[index])
//                .append(System.currentTimeMillis())
                .append('-')
                .append(appender)
                .toString();
    }

    /**
     * @param number 数字输初始值
     * @param limit  限定长度
     * @return
     */
    public static String generateLimitNumberStr(int number, int limit) {

        String number_ = "" + number, prefix = "";
        if (number_.length() == limit) {
            prefix = number_ + "";
        } else if (number_.length() > limit) {
            throw new Error("数字长度超出限定长度!");
        } else {
            for (int i = 0; i < (limit - number_.length()); i++) {
                prefix += "0";
            }
            prefix += number_;
        }
        return prefix;
    }

    ;


    public static String generateSmsCode() {
        String str = "";
        for (int i = 1; i < 7; i++) {
            str += new Random().nextInt(9);
        }
        System.out.println(str);
        return str;
    }


    public static Map<String, Object> toMap(String path) throws UnsupportedEncodingException, URISyntaxException {
        path = java.net.URLDecoder.decode(path, "UTF-8");
        URI uri = new URI(path);
        Map<String, Object> map = new HashedMap();
        String strQuery = uri.getQuery();
        if (strQuery == null) {
            return map;
        }
        String[] str = strQuery.split("&");
        for (String st : str) {
            String[] smap = st.split("=");
            map.put(smap[0], smap[1]);
        }
        return map;
    }


    /**
     * @return 形如 yyyyMMddHHmmssSSS-Z0000019558195832297 的(38位)保证唯一的递增的序列号字符串，
     * 主要用于数据库的主键，方便基于时间点的跨数据库的异步数据同步。
     * 前半部分是currentTimeMillis，后半部分是nanoTime（正数）补齐20位的字符串，
     * 如果通过System.nanoTime()获取的是负数，则通过nanoTime = nanoTime+Long.MAX_VALUE+1;
     * 转化为正数或零。
     */
    public static String getTimeMillisSequence() {
        long nanoTime = System.nanoTime();
        String preFix = "";
        if (nanoTime < 0) {
            preFix = "A";//负数补位A保证负数排在正数Z前面,解决正负临界值(如A9223372036854775807至Z0000000000000000000)问题。
            nanoTime = nanoTime + Long.MAX_VALUE + 1;
        } else {
            preFix = "Z";
        }
        String nanoTimeStr = String.valueOf(nanoTime);

        int difBit = String.valueOf(Long.MAX_VALUE).length() - nanoTimeStr.length();
        for (int i = 0; i < difBit; i++) {
            preFix = preFix + "0";
        }
        nanoTimeStr = preFix + nanoTimeStr;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); //24小时制
        String timeMillisSequence = sdf.format(System.currentTimeMillis()) + "-" + nanoTimeStr;

        return timeMillisSequence;
    }

    public static String getUSER() {
        return USER;
    }

    public static String getPhoneCode() {
        return PHONE_CODE;
    }

    public static String getCurrentWxUser() {
        return CURRENT_WX_USER;
    }

    public static String getCurrentSp() {
        return CURRENT_SP;
    }

    public static String getSHARE() {
        return SHARE;
    }

    public static String getLoginTypePc() {
        return LOGIN_TYPE_PC;
    }

    public static String getLoginTypeWx() {
        return LOGIN_TYPE_WX;
    }

    public static String getKaptchaSessionKey() {
        return KAPTCHA_SESSION_KEY;
    }

    public static String getOrderpaperPath() {
        return orderpaperPath;
    }

    public static void setOrderpaperPath(String orderpaperPath) {
        Constants.orderpaperPath = orderpaperPath;
    }

    public static String getThumbnailPath() {
        return thumbnailPath;
    }

    public static void setThumbnailPath(String thumbnailPath) {
        Constants.thumbnailPath = thumbnailPath;
    }

    public static String getNginxVisitUrl() {
        return nginxVisitUrl;
    }

    public static void setNginxVisitUrl(String nginxVisitUrl) {
        Constants.nginxVisitUrl = nginxVisitUrl;
    }

    public static String getToken() {
        return token;
    }

    public static void setToken(String token) {
        Constants.token = token;
    }

    public static String getEncodingAESKey() {
        return encodingAESKey;
    }

    public static void setEncodingAESKey(String encodingAESKey) {
        Constants.encodingAESKey = encodingAESKey;
    }

    public static String getUrl() {
        return url;
    }

    public static void setUrl(String url) {
        Constants.url = url;
    }

    public static String getApikey() {
        return apikey;
    }

    public static void setApikey(String apikey) {
        Constants.apikey = apikey;
    }

    public static String getTmpid() {
        return tmpid;
    }

    public static void setTmpid(String tmpid) {
        Constants.tmpid = tmpid;
    }

    public static String getDomain() {
        return domain;
    }

    public static void setDomain(String domain) {
        Constants.domain = domain;
    }

    public static String getSlat() {
        return slat;
    }

    public static String getTmplCreateOrder() {
        return tmplCreateOrder;
    }

    public static void setTmplCreateOrder(String tmplCreateOrder) {
        Constants.tmplCreateOrder = tmplCreateOrder;
    }

    public static String getSuperManagerRoleId() {
        return SUPER_MANAGER_ROLE_ID;
    }

    public static String getWXUserTypeWX() {
        return WXUserTypeWX;
    }

    public static String getWXUserTypePC() {
        return WXUserTypePC;
    }

    public static String getTmplUpdateOrderStatus() {
        return tmplUpdateOrderStatus;
    }

    public static void setTmplUpdateOrderStatus(String tmplUpdateOrderStatus) {
        Constants.tmplUpdateOrderStatus = tmplUpdateOrderStatus;
    }

    public static String getTmplReturnedCommission() {
        return tmplReturnedCommission;
    }

    public static void setTmplReturnedCommission(String tmplReturnedCommission) {
        Constants.tmplReturnedCommission = tmplReturnedCommission;
    }

    public static String getTmplApplyServiceSuccess() {
        return tmplApplyServiceSuccess;
    }

    public static void setTmplApplyServiceSuccess(String tmplApplyServiceSuccess) {
        Constants.tmplApplyServiceSuccess = tmplApplyServiceSuccess;
    }

    public static String getTmplWithDrawSuccess() {
        return tmplWithDrawSuccess;
    }

    public static void setTmplWithDrawSuccess(String tmplWithDrawSuccess) {
        Constants.tmplWithDrawSuccess = tmplWithDrawSuccess;
    }

    public static String getTmplUpdateOrderPrice() {
        return tmplUpdateOrderPrice;
    }

    public static void setTmplUpdateOrderPrice(String tmplUpdateOrderPrice) {
        Constants.tmplUpdateOrderPrice = tmplUpdateOrderPrice;
    }

    public static String getTmplNewVipJoin() {
        return tmplNewVipJoin;
    }

    public static void setTmplNewVipJoin(String tmplNewVipJoin) {
        Constants.tmplNewVipJoin = tmplNewVipJoin;
    }
}
